/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.vod.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * 
 * @author dRazanakoto
 */
public class SenderMulticast extends Sender {

	private MulticastSocket socket;

	/**
	 * 
	 * @param ip
	 * @param port
	 * @throws Exception
	 */
	public SenderMulticast(InetAddress ip, int port) throws Exception {
		super(ip, port);
		socket = new MulticastSocket();
		startWatching();
	}
	
	@Override
	public void close() {
		if (!socket.isClosed())
			socket.close();
	}

	/**
	 * 
	 * @param msg
	 * @throws IOException
	 */
	@Override
	public void send(String msg) throws Exception {
		byte[] bytes;
		DatagramPacket packet;
		bytes = msg.getBytes("UTF-8");
		packet = new DatagramPacket(bytes, bytes.length, ip, port);
		socket.send(packet);

		addSentBytes(packet.getLength(), System.currentTimeMillis());
	}

	@Override
	public void send(byte[] msg) throws Exception {
		DatagramPacket packet = new DatagramPacket(msg, msg.length, ip, port);
		socket.send(packet);
		addSentBytes(packet.getLength(), System.currentTimeMillis());
	}
}
